package com.junko.api.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.junko.api.annotation.UserAccess;
import com.junko.api.tool.ToolJWT;
import com.junko.core.exception.LockedException;
import com.junko.core.exception.NoLoginException;
import com.junko.core.tool.ToolDateTime;
import com.junko.model.app.User;
import com.junko.service.app.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

public class NeedUserTokenInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LogManager.getLogger(NeedUserTokenInterceptor.class);

    @Resource
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 从方法处理器中获取出要调用的方法
            Method method = handlerMethod.getMethod();
            // 获取出方法上的Access注解
            UserAccess userAccess = method.getAnnotation(UserAccess.class);
            if (userAccess == null) {
                // 如果注解为null说明不需要拦截, 直接放过
                return true;
            }
            String token = request.getHeader("user_token");
            if (StringUtils.isEmpty(token)) {
                logger.error("token参数缺失");
                throw new NoLoginException("请登录后再操作");
            }
            DecodedJWT decodedJWT = ToolJWT.verify(token);
            if (decodedJWT == null) {
                logger.error("token无效");
                throw new NoLoginException("请登录后再操作");
            }
            Date date = decodedJWT.getExpiresAt();
            //过期了
            if (date != null && ToolDateTime.compare(date, new Date()) <= 0) {
                logger.error("token已过期");
                throw new NoLoginException("请登录后再操作");
            }
            String id = decodedJWT.getClaims().get("id").asString();
            User user = userService.selectByPrimaryKey(id);
            if (user == null) {
                logger.error("用户不存在");
                throw new NoLoginException("请登录后再操作");
            }
            if (user.getLocked()) {
                logger.error("用户被禁用");
                throw new LockedException();
            }
            logger.error("当前用户user=",user);
            return true;
        }
        return true;
    }
}
